package com.annual.system.service.impl;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.annual.common.exception.ServiceException;
import com.annual.common.utils.Assert;
import com.annual.common.utils.SecurityUtils;
import com.annual.common.utils.StringUtils;
import com.annual.common.utils.bean.BeanUtils;
import com.annual.system.domain.EnterpriseBusiness;
import com.annual.system.domain.Order;
import com.annual.system.dto.enterpriseBusiness.*;
import com.annual.system.mapper.EnterpriseBusinessMapper;
import com.annual.system.mapper.SysPostMapper;
import com.annual.system.service.IEnterpriseBusinessService;
import com.annual.system.service.IOrderService;
import com.annual.system.service.ISysConfigService;
import com.annual.system.service.ISysDictDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 业务表 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-12-02
 */
@Service
public class EnterpriseBusinessServiceImpl  extends ServiceImpl<EnterpriseBusinessMapper, EnterpriseBusiness> implements IEnterpriseBusinessService {

    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IOrderService orderService;
    @Override
    public ResAppEnterpriseBusinessDto addBusiness(ReqAppEnterpriseBusinessDto req) {
        if(req.getType() == 1){
            if(req.getRatal() == null){
                throw new ServiceException("纳税额不能为空");
            }
            if(req.getRatal().compareTo(BigDecimal.ZERO) < 0){
                throw new ServiceException("纳税额最小为0");
            }
            if(req.getTurnover() == null){
                throw new ServiceException("年营业额不能为空");
            }
            if(req.getTurnover().compareTo(BigDecimal.ZERO) < 0){
                throw new ServiceException("年营业额最小为0");
            }
        }
        Long userId = SecurityUtils.getUserId();
        EnterpriseBusiness enterpriseBusiness = new EnterpriseBusiness();
        BeanUtils.copyProperties(req,enterpriseBusiness);
        enterpriseBusiness.setType(req.getType());
        enterpriseBusiness.setUserId(userId);
        enterpriseBusiness.setCreateTime(LocalDateTime.now());
        enterpriseBusiness.insert();
        //添加订单
        Order order = new Order();
        order.setOrderType(1);
        order.setCreateTime(LocalDateTime.now());
        order.setUserId(userId);
        order.setEnterpriseBusinessId(enterpriseBusiness.getId());
        //获取价格
        BigDecimal price = getPrice(req.getType());
        order.setType(req.getType());
        order.setFee(price);
        order.setPrice(price);
        order.setStatus(1);
        order.setOutTradeNo(UUID.fastUUID().toString().replaceAll("-",""));
        order.insert();
        ResAppEnterpriseBusinessDto resData = new ResAppEnterpriseBusinessDto();
        BeanUtils.copyProperties(enterpriseBusiness,resData);
        resData.setPrice(price);
        resData.setOrderId(order.getOrderId());
        return resData;
    }

    @Override
    public BigDecimal getPrice(Integer type){
        String configKey = "";
        if(type == 1){
            configKey = "price.report";
        }
        if(type == 2){
            configKey = "price.cancel";
        }
        if(type == 3){
            configKey = "price.fix";
        }
        if(StringUtils.isBlank(configKey)){
            throw new ServiceException("获取价格异常：没有对应缓存KEY");
        }
        String value = sysConfigService.selectConfigByKey(configKey);
        if(StringUtils.isBlank(value)){
            throw new ServiceException("获取价格异常：没有获取到配置");
        }
        //价格随机
        String price = StrUtil.splitTrim(value,".").get(0);
        //角分随机
        int jiao = RandomUtil.randomInt(1,9);
        int fen = RandomUtil.randomInt(1,9);
        price = price+"."+jiao+fen;
        try {
            return BigDecimal.valueOf(Double.parseDouble(price));
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("获取价格异常：价格转换异常");
        }
    }

    @Override
    public List<ResAppEnterpriseBusinessListDto> appList(ReqAppEnterpriseBusinessListDto req) {
        req.setUserId(SecurityUtils.getUserId());
        List<ResAppEnterpriseBusinessListDto> data = baseMapper.appList(req);
        for (ResAppEnterpriseBusinessListDto datum : data) {
            Order order = orderService.getLastOrder(datum.getId());
            if(order != null){
                datum.setStatus(order.getStatus());
                datum.setFee(order.getFee());
            }
        }
        return data;
    }

    @Override
    public List<ResEnterpriseBusinessListDto> pcList(ReqEnterpriseBusinessListDto req) {
        List<ResEnterpriseBusinessListDto> data = baseMapper.pcList(req);
        for (ResEnterpriseBusinessListDto datum : data) {
            datum.setType(getTypeName(Integer.parseInt(datum.getType())));
            //datum.setStatus(orderService.getStatusName(datum.getStatus()));
        }
        return data;
    }

    @Override
    public ResEnterpriseBusinessInfoDto getInfo(Long enterpriseBusinessId) {
        EnterpriseBusiness enterpriseBusiness = getById(enterpriseBusinessId);
        Assert.notNull(enterpriseBusiness,"未查到相关信息");
        ResEnterpriseBusinessInfoDto infoDto = new ResEnterpriseBusinessInfoDto();
        BeanUtils.copyProperties(enterpriseBusiness,infoDto);
        infoDto.setEnterpriseBusinessId(enterpriseBusiness.getId());
        Order order = orderService.getLastOrder(enterpriseBusiness.getId());
        if(order != null){
            infoDto.setStatus(order.getStatus());
        }
        return infoDto;
    }

    @Override
    public void edit(ResEnterpriseBusinessUpdateDto dto) {
        EnterpriseBusiness enterpriseBusiness = getById(dto.getEnterpriseBusinessId());
        Assert.notNull(enterpriseBusiness,"未查到相关信息");
        enterpriseBusiness.setEnterpriseName(dto.getEnterpriseName());
        enterpriseBusiness.setCreditCode(dto.getCreditCode());
        enterpriseBusiness.setLegalPersonName(dto.getLegalPersonName());
        enterpriseBusiness.setIdCard(dto.getIdCard());
        enterpriseBusiness.setPhone(dto.getPhone());
        enterpriseBusiness.setRatal(dto.getRatal());
        enterpriseBusiness.setTurnover(dto.getTurnover());
        enterpriseBusiness.setRemark(dto.getRemark());
        enterpriseBusiness.setUpdateTime(LocalDateTime.now());
        Order order = orderService.getLastOrder(enterpriseBusiness.getId());
        if(order!=null){
            order.setStatus(dto.getStatus());
            order.updateById();
        }
        enterpriseBusiness.updateById();
    }

    @Override
    public String getTypeName(Object objType){
        Integer type = Integer.parseInt(objType.toString());
        if(type == 1){
            return  "执照年报";
        }
        if(type == 2){
            return  "执照注销";
        }
        if(type == 3){
            return  "信用修复";
        }
        return "其他"+type;
    }



}
